/// <reference path="../typings/globals/jquery/index.d.ts" />

'use strict'
var fs = require('fs') // 加载File System读写模块
var iconv = require('iconv-lite'); // 加载编码转换模块
var Test = require('./test.js')

// 加载JS绑定Python调用协议模块
var pyRequest = (function() {
    // 加载第三方python库
    let python = require("./lib/binding")
    // 此时执行Python
    let sys = python.import('sys');
    let os = python.import('os');

    if (typeof(__dirname) != 'undefined') {
        sys.path.append(os.path.join(__dirname, '../client'))
    }

    return python.import('Request');
})()

var requestObject = pyRequest.ClientRequest()
requestObject.startupNodeJS() // 加载界面时

// 写入文件
function writeFile(file, data, encoding) {
    let arr = iconv.encode(data, encoding); // 把中文转换成字节数组
    fs.writeFileSync(file, arr); // 如果用writeFile，那么会删除旧文件，直接写新文件    
}

// 读取文件
function readFile(file, encoding) {
    if (fs.existsSync(file)) {
        return iconv.decode(fs.readFileSync(file), encoding); // 把数组转换为gbk中文  
    } else {
        return null
    }
}

// 创建进度条元素样式
function createProgress(addrs) {
    $('#build-status').empty()

    for (let i = 0; i < addrs.length; i++) {
        let addr = addrs[i]
        // 创建进度容器
        let html = '<div class="progress-content">\
                        <div class="progress">\
                        <b class="progress__bar">\
                            <span class="progress__text">' +
            addr + ': <em>0%</em></span>' +
            '</b>\
                        </div>\
                        <div class="log" id="' + addr + '"></div>\
                    </div>'
        $('#build-status').append(html)
    }
}

// 界面上创建进度条空间，添加一个进度特效
function createProgressUI(configures) {
    let addrs = []
    for (let i = 0; i < configures.length; i++) {
        let configure = configures[i];

        if (addrs.indexOf(configure.specifyslave) == -1)
            addrs.push(configure.specifyslave)
    }

    // 创建实例进度按钮
    createProgress(addrs)

    // 添加事件监听
    $('#build-status>.progress-content').bind(TreeEvent.progressExpand())

    Test.testProgress()
}

// 设置定时器
function setupTimmer() {
    // 通知服务器开启状态监测
    var timmer = setInterval(function() {
        if (requestObject.already) {
            requestObject.openSlaveMonitor()
            clearInterval(timmer)
        }
    }, 200)

    // 定时刷新界面连接状态, 1秒更新一次
    setInterval(function() {
        $('#slave-addr').children().each((index, element) => {
            let select = element.getElementsByTagName('select')[0],
                lable = element.getElementsByTagName('lable')[0],
                cbIdx = select.selectedIndex,
                addr = select.options[cbIdx].value

            let state = requestObject.slaveState(addr)
            for (let i = 0; i < lable.classList.length; i++) {
                lable.classList.remove(lable.classList.item(i))
            }

            lable.innerHTML = state
            lable.classList.add(state)
        })
    }, 1000)
}

// 设置页面1 编译版本勾选的设置
function setupMasterCheck(obj) {
    let id = String(obj.name).replace('task_cad_', '')
    let cbDivIdx = $('#cad-version-config input[type=checkbox]').index($('#' + id))
    $('#' + id).get(0).checked = true
    let addrCb = $('#slave-addr select').get(cbDivIdx)

    for (let i = 0; i < addrCb.options.length; i++) {
        if (addrCb.options[i].value == obj.specifyslave) {
            addrCb.options[i].selected = true;
        }
    }
}

// 设置页面3 地方插件勾选的设置
function setupPluginCheck(obj) {
    $('#plugin-target input[type=checkbox]').each((index, element) => {
        element.checked = false
        let parent = element.parentElement
        for (let i = 0; i < obj.plugins.length; i++) {
            if (parent.id.length != 0 && obj.plugins[i].indexOf(parent.id) != -1) {
                element.checked = true
            }
        }
    })
}

// 设置页面3 编译选项设置
function setupCompileOption(obj) {
    $('#svn>input[type=text]').val(obj.svn)
    $('#subversion>input[type=text]').val(obj.subversion)
    $('#master>input[type=text]').val(obj.master)
    $('#username>input[type=text]').val(obj.username)
    $('#password>input[type=password]').val(obj.password)
    $('#localpath>input[type=text]').val(obj.localpath)
    $('#parallelcount>input[type=text]').val(obj.parallelcount)
    $('#serverpath>input[type=text]').val(obj.serverpath)
    $('#productversion>input[type=text]').val(obj.productversion)
    $('#productname>input[type=text]').val(obj.productname)

    document.getElementById('forcecheck').checked = obj.forcecheck
    document.getElementById('signdll').checked = obj.signdll
    document.getElementById('backuppdb').checked = obj.backuppdb
    document.getElementById('rebuild').checked = obj.rebuild
    document.getElementById('dontcleanobj').checked = obj.dontcleanobj
}


// 用户配置加载
exports.load = function() {
    let json = readFile('configure.json', 'gbk')
    if (!json) {
        return
    }

    let objArr = JSON.parse(json)
    $('#cad-version-config input[type=checkbox]').each((index, element) => {
        element.checked = false
    })

    for (let i = 0; i < objArr.length; i++) {
        let obj = objArr[i];
        // 设置页面1的数据
        setupMasterCheck(obj)
    }

    // 设置页面2 和页面3 数据
    if (objArr.length != 0) {
        setupPluginCheck(objArr[0])
        setupCompileOption(objArr[0])
    }

    // 初始化界面使用的一些定时器，包括状态刷新，数据获取等
    setupTimmer()
}

// 用户配置修改保存
exports.save = function() {
    let savedata = []
    console.log('开始生成打包配置文件...')

    // 页面1 提供数据
    let collectFormOne = function(index, element) {
        let obj = {}
        let configure, platform, out
        let parent = element.parentElement
        if (!parent.hasAttribute('Out') || !element.checked) {
            return // 节点为非叶子节点或者未被选中，跳过
        }

        obj.name = 'task_cad_' + element.id // 任务名称
        configure = parent.getAttribute('Configuration')
        platform = parent.getAttribute('Platform')
        out = parent.getAttribute('Out')

        obj.configuration = {
            "Mushroom.sln": [{
                Configuration: configure,
                Platform: platform,
                OutDir: out
            }]
        }

        let addrDiv = $('#slave-addr').children()[index],
            addrCombo = addrDiv.getElementsByTagName('select')[0],
            cbIdx = addrCombo.selectedIndex

        obj.specifyslave = addrCombo.options[cbIdx].value // 指定计算机

        // 页面2 提供数据
        let collectFormTwo = function(index, element) {
            let parent = element.parentElement
            if (!parent.hasAttribute('Out')) {
                return // 节点为非叶子节点或者未被选中，跳过
            }

            let label = element.nextElementSibling
            obj.plugins.push('地方插件/' + label.innerHTML + '/')

            obj.pluginconfiguration[label.innerHTML + '.sln'] = [{
                Configuration: configure,
                Platform: platform,
                OutDir: String(out).replace('Bin/', 'Bin/' + label.innerHTML + '/') + 'Plugin/'
            }]
        }

        obj.plugins = []
        obj.pluginconfiguration = {}
        $('#plugin-target input[type=checkbox]:checked').each(collectFormTwo)

        // 页面3 提供数据
        obj.master = $('#master>input[type=text]').val()
        obj.svn = $('#svn>input[type=text]').val()
        obj.subversion = $('#subversion>input[type=text]').val()
        if (obj.subversion.length === 0) {
            obj.subversion = null
        }

        obj.username = $('#username>input[type=text]').val()
        obj.password = $('#password>input[type=password]').val()
        obj.localpath = $('#localpath>input[type=text]').val()
        obj.serverpath = $('#serverpath>input[type=text]').val()
        obj.parallelcount = Number($('#parallelcount>input[type=text]').val())
        obj.productversion = $('#productversion>input[type=text]').val()
        if (obj.productversion.length === 0) {
            obj.productversion = null
        }

        obj.productname = $('#productname>input[type=text]').val()

        obj.forcecheck = $('#forcecheck').get(0).checked
        obj.signdll = $('#signdll').get(0).checked
        obj.backuppdb = $('#backuppdb').get(0).checked
        obj.rebuild = $('#rebuild').get(0).checked
        obj.dontcleanobj = $('#dontcleanobj').get(0).checked

        obj.files_subversion = {}
        obj.errlist = []
        obj.asfastas = true
        savedata.push(obj)
    }

    $('#cad-version-config input[type=checkbox]').each(collectFormOne)
    let str = JSON.stringify(savedata, null, 4)
    console.log(str)

    createProgressUI(savedata)
    writeFile('configure.json', str, 'gbk')
}


// 提交打包请求，执行Python脚本
exports.request = function() {
    var timer1 = setInterval(function() {
        if (requestObject.already) {
            requestObject.submit()
            clearInterval(timer1)
        }
    }, 200)

    // 切换到“构建状态”页面
    $('.tab-wrapper input[type=radio]').each((index, element) => {
        element.checked = element.id === 'tab-radio-4'
    })

    let timer2 = setInterval(function() {
        if (requestObject.isover()) {
            clearInterval(timer2)
        }

        // 定时获取构建日志并输出到"构建状态"页面中各Slave的日志区域
        $('#build-status .log').each((index, element) => {
            let message = requestObject.getmessage(element.id)
            if (message) {
                let pre = document.createElement('pre')
                pre.appendChild(document.createTextNode(message))
                element.appendChild(pre)
                element.scrollTop = element.scrollHeight;
            }
        })
    }, 200)
}
